//index.js
import Poster from '../../poster-plugin/poster/poster';
const posterConfig = require('../../config/poster.js');
const util = require('../../utils/util.js');
const date_util = require('../../utils/date_util.js');
const api = require('../../config/api.js');
const user = require('../../services/user.js');
var Moment = require("../../utils/Moment.js"); //时间控件
var event = require('../../utils/event.js');
const posterActivityConfig = posterConfig.getPosterActivityCinfig()
const app = getApp()
var DATE_LIST = [];
var DATE_YEAR = new Date().getFullYear();
var DATE_MONTH = new Date().getMonth() + 1;
var DATE_DAY = new Date().getDate();
const navigationBarHeight = (getApp().statusBarHeight + 44) + 'px'
import ColorThief from '../../utils_color/color-thief.js'
import {
  rgbToHex,
  uuid,
  colorsEqual,
  saveBlendent,
  getPicColor
} from '../../utils_color/util.js'

Page({
  data: {
    posterSendConfig: posterActivityConfig.jdConfig,
    navigationBarHeight,
    statusBarHeight: app.statusBarHeight + 'px',
    tabbar: {},
    page: 1,
    size: 5,
    curIndex: 0,
    //时间
    isShowDate: false,
    maxMonth: 36, //最多渲染月数
    dateList: [],
    systemInfo: {},
    isIphoneX: app.globalData.isIphoneX ? true : false,
    weekStr: ['日', '一', '二', '三', '四', '五', '六'],
    checkInDate: Moment(new Date()).format('YYYY-MM-DD'),
    checkOutDate: Moment(new Date()).add(7, 'day').format('YYYY-MM-DD'),
    checkInDateStr: Moment(new Date()).format('MM.DD'),
    checkOutDateStr: Moment(new Date()).add(7, 'day').format('MM.DD'),
    markcheckInDate: false, //标记开始时间是否已经选择
    markcheckOutDate: false, //标记结束时间是否已经选择
    dateScroll: 'flag' + Moment(new Date()).format('YYYYMM_DD'), //定位初始时 时间停留位置
    userInfo: app.globalData.userInfo,
    hasUserInfo: app.globalData.hasUserInfo,
    auth: app.globalData.auth,
    hasPhone: app.globalData.hasPhone,
    uphidden: true,
    hidden: true,
    list: [],
    newList: [],
    toView: '',
    scrollHeight: 0,
    scrollTopDate: 0,
    hiddenAll: true,
    hiddenShare: true,
    hiddenNavigation: true,
    hiddenWxShare: true,
    sharepicurl: '',
    shareindex: 0,
    flag: 0, //是否扫码进去
    faAutoplay: false,
    faIndicatorDots: false,
    preIndex: 0,
    //结果返回
    showPage: false,
    marginWidth: 0,
  },

  launchAppError: function(e) {
    wx.getSystemInfo({
      success: function(res) {
        let type = res.system
        if (type.indexOf("Android") != -1) {
          wx.showModal({
            title: '跳转至同感App',
            showCancel: false,
            content: '亲爱的主人，很遗憾,同感app暂时未支持您的设备类型,您还是在小程序里尽情玩耍吧！'
          })
        }
        if (type.indexOf("iOS") != -1) {
          wx.showModal({
            title: '跳转至同感App',
            showCancel: false,
            content: '亲爱的主人，请到AppStore里下载同感App查看更多同感动态！'
          })
        }
      }
    })
  },


  onLoad: function(options) {

    this.colorThief = new ColorThief('canvasidii');
    wx.hideTabBar();
    app.editTabbar();
    const scene = decodeURIComponent(options.scene)
    if ((typeof(scene) != undefined) && scene != 'undefined') {
      this.setData({
        flag: 0
      })
    } else {
      this.setData({
        flag: 1
      })
    }
    wx.getUpdateManager().onCheckForUpdate(function(res) {
      console.log("是否有新版本：" + res.hasUpdate);
      if (res.hasUpdate) {
        wx.getUpdateManager().onUpdateReady(function() {
          wx.showModal({
            title: '更新提示',
            content: '新版本已经准备好，单击确定重启应用',
            showCancel: false,
            success: function(res) {
              if (res.confirm) {
                wx.getUpdateManager().applyUpdate();
              }
            }
          })
        })
        wx.getUpdateManager().onUpdateFailed(function() {
          wx.showModal({
            title: '提示',
            content: '检查到有新版本，但下载失败，请检查网络设置',
            showCancel: false,
          })
        })
      }
    });
    var that = this;
    this.createDateListData();
    var _this = this;
    var checkInDate = options.checkInDate ? options.checkInDate : Moment(new Date()).format('YYYY-MM-DD');
    var checkOutDate = options.checkOutDate ? options.checkOutDate : Moment(new Date()).add(1, 'day').format('YYYY-MM-DD');
    that.GetList(that, 1);

    wx.showShareMenu({ // 要求小程序返回分享目标信息      
      withShareTicket: true
    });
    // wx.hideShareMenu();

    wx.getSystemInfo({
      success: function(res) {
        _this.setData({
          scrollHeight: (res.windowHeight),
          systemInfo: res,
          marginWidth: (res.windowWidth - 166) / 2
        });
      }
    })
    event.on('DataChanged', self, this.onDataChanged); //监听
    event.on('AuthChanged', self, this.onAuthChanged);
  },

  onReady: function() {

  },

  onShow: function() {
    var that = this
    if (app.globalData.checkLogin) {
      that.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: app.globalData.hasUserInfo,
        auth: app.globalData.auth,
        hasPhone: app.globalData.hasPhone,
      });
    } else {
      app.checkLoginReadyCallback = res => {
        that.setData({
          userInfo: app.globalData.userInfo,
          hasUserInfo: app.globalData.hasUserInfo,
          auth: app.globalData.auth,
          hasPhone: app.globalData.hasPhone,
        });
      };
      
    }    
  },
  onHide: function() {},

  onUnload: function() {
    event.remove('DataChanged', self, this.onDataChanged);
    event.remove('AuthChanged', self, this.onAuthChanged);
  },

  onMyevent: function(e) {
    this.setData({
      userInfo: e.detail.paramBtoA.userInfo,
      hasUserInfo: e.detail.paramBtoA.hasUserInfo,
      auth: e.detail.paramBtoA.auth,
      hasPhone: e.detail.paramBtoA.hasPhone,
    })
    this.GetList(this, 1);
  },

  dealnewData: function(newDataArr) {
    if (newDataArr && newDataArr.length > 0) {
      var list = this.data.list;
      for (var i = 0; i < newDataArr.length; i++) {
        var act = newDataArr[i].activity
        var venue = newDataArr[i].venue
        if (venue) {
          act.area = venue.name
        }
        act.venue = venue;
        var begin = date_util.convertTime(act.beginTime);
        var end = date_util.convertTime(act.endTime);
        var title_str = act.name.length > 17 ? act.name.substr(0, 16) + '...' : act.name;
        act.followers = newDataArr[i].followUsers
        act.begin = begin
        act.end = end
        act.title_str = title_str
        act.acti_photo = act.coverUrl +
          "?imageMogr2/thumbnail/" +
          370 +
          "x" +
          "/format/jpg/size-limit/80k!";
        act.hasCollect = newDataArr[i].followed > 0 ? true : false
        act.collectCount = newDataArr[i].followUserCount
        list.push(act);
      }

      this.setData({
        list: list,
        showPage: true
      })
    } else {
      this.setData({
        showPage: true
      })
    }
  },

  showLoadTip: function() {
    wx.showLoading({
      title: '正在加载中...',
      mask: true
    })
  },

  NextPageLoadTip: function() {
    wx.showLoading({
      title: '加载更多数据...',
      mask: true
    })
  },
  RefreshLoadTip: function() {
    wx.showLoading({
      title: '正在刷新中...',
      mask: true
    })
  },
  NoMoreLoadTip: function() {
    wx.showToast({
      title: '暂无更多数据',
      icon: 'loading'
    })
  },
  GetList: function(that, type) {
    var pageNew = that.data.page + 1;
    if (type == 1) {
      that.RefreshLoadTip()
      that.setData({
        page: 1,
      })
    }
    if (type == 2) {
      that.NextPageLoadTip()
      that.setData({
        page: pageNew,
      })
    }

    util.pututrequest(api.activityUrl + '?page=' + that.data.page, 'GET').then(res => {
      if (res && res.code == 200) {
        if (type == 1) {
          that.setData({
            uphidden: true,
            newList: res.data,
            list: [],
            curIndex: 0,
          })

        }
        if (type == 2) {
          that.setData({
            newList: res.data,
          })
        }

        that.dealnewData(that.data.newList)

        if (that.data.newList.length <= 0) {
          that.NoMoreLoadTip()
        }

        setTimeout(function() {
          wx.hideLoading()
        }, 1000)
      } else {
        wx.hideLoading()
        if (type == 1) {
          that.setData({
            list: [],
            newList: [],
            showPage: true
          });
        }
      }

    });
  },

  // 处理分享海报
  updateActivityPosterConfig: function(bgColor, avatar, nickName, coverUrl, activityName, rest, venue, label, qrcode) {
    posterActivityConfig.jdConfig.backgroundColor = bgColor
    posterActivityConfig.jdConfig.images[0].url = avatar
    posterActivityConfig.jdConfig.texts[0].text = nickName
    posterActivityConfig.jdConfig.images[1].url = coverUrl
    posterActivityConfig.jdConfig.texts[1].text = activityName

    if (posterActivityConfig.jdConfig.texts.length < 5) {
      posterActivityConfig.jdConfig.texts.splice(2, 0, {
        x: 672,
        y: 1225,
        baseLine: 'right',
        text: '18天',
        fontSize: 32,
        bold: true,
        width: 74,
        color: '#000000',
        zIndex: 100,
      });

      posterActivityConfig.jdConfig.texts.splice(4, 0, {
        x: 662,
        y: 1265,
        baseLine: 'right',
        width: 74,
        text: '倒计时',
        fontSize: 22,
        color: '#4A4A4A',
        zIndex: 100,
      });
    }
    if (rest.day > 0) {
      posterActivityConfig.jdConfig.texts[2].text = rest.day + '天'
    } else if (rest.hour > 0) {
      posterActivityConfig.jdConfig.texts[2].text = rest.hour + '小时'
    } else if (rest.minute > 0) {
      posterActivityConfig.jdConfig.texts[2].text = rest.minute + '分钟'
    }
    posterActivityConfig.jdConfig.texts[1].width = 400
    posterActivityConfig.jdConfig.texts[3].text = venue ? venue : ''
    posterActivityConfig.jdConfig.texts[4].text = label
    posterActivityConfig.jdConfig.images[2].url = qrcode
  },

  sharePic: function(e) {
    var that = this
    that.auth = that.selectComponent("#auth");
    if (that.data.auth && that.data.hasPhone) {
      let index = e.currentTarget.dataset.index
      that.setData({
        shareindex: index,
        hiddenAll: false,
        hiddenNavigation: false
      })
    } else {
      that.auth.showAuth()
    }
  },

  close_share: function(e) {
    this.setData({
      hiddenShare: true,
      hiddenNavigation: true,
      hiddenWXShare: true,
      hiddenAll: true,
      sharepicurl: ''
    })
  },

  generatePoster: function() {
    var that = this
    that.getSharePoster(that.data.shareindex)
    that.setData({
      hiddenShare: false,
      hiddenNavigation: true,
      hiddenWXShare: true,
      sharepicurl: ''
    })
  },
  saveWX: function() {
    var that = this
    that.setData({
      hiddenShare: false,
      hiddenNavigation: true,
      hiddenWXShare: false
    })
  },

  generateWXPoster: function() {
    var that = this
    that.getSharePoster(that.data.shareindex)
    that.setData({
      hiddenShare: true,
      hiddenNavigation: true,
      hiddenWXShare: false
    })
  },

  getSharePoster: function(index) {
    let that = this
    let activity = that.data.list[index]
    activity.rest = date_util.getRemainderTime(activity.beginTime)
    wx.showLoading({
      title: '生成海报...',
      mask: true,
    })
    util.pututrequest(api.generateQrcode, 'POST', {
      id: activity.id,
      type: 'ACTIVITY'
    }).then(res => {
      if (res && res.code == 200) {
        let qrcode = res.data.url
        if (qrcode) {
          const imagePath = activity.coverUrl
          getPicColor(imagePath, this.colorThief).then(res => {
            //画图
            that.updateActivityPosterConfig(res, that.data.userInfo.avatarUrl, that.data.userInfo.nickname, activity.coverUrl, activity.name, activity.rest, activity.area, '倒计时', qrcode)

            that.setData({
              posterSendConfig: posterActivityConfig.jdConfig
            }, () => {
              Poster.create(true); // 入参：true为抹掉重新生成 
            });
            // 画图  
          })

        } else {
          wx.showModal({
            title: '二维码获取失败',
            showCancel: false,
            content: '该活动海报的二维码获取失败,请重新生成！'
          })
        }

      }
    });
  },

  onPosterSuccess(e) {
    const {
      detail
    } = e;
    this.setData({
      hiddenShare: false,
      sharepicurl: detail
    })
    wx.hideLoading()
  },
  onPosterFail(err) {
    console.error(err);
  },

  saveNetPicToLocal: function() {
    let that = this
    wx.showLoading({
      title: '正在保存',
      mask: true,
    })
    //图片保存到本地
    console.log(that.data.sharepicurl)
    wx.saveImageToPhotosAlbum({
      filePath: that.data.sharepicurl,
      success: function(data) {
        wx.showModal({
          title: '保存成功',
          content: '活动海报保存到相册成功',
          confirmText: "我知道了",
          showCancel: false,
        })
      },
      fail: function(err) {
        console.log(err)
        if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
          wx.openSetting({
            success(settingdata) {
              console.log(settingdata)
              if (settingdata.authSetting['scope.writePhotosAlbum']) {
                wx.showToast({
                  title: '授权成功，继续保存',
                  icon: 'success',
                  duration: 2000
                })
              } else {
                wx.showToast({
                  title: '未授权，无法保存',
                  icon: 'success',
                  duration: 2000
                })
              }
            }
          })
        }
      },
    })
    wx.hideLoading()
  },

  onShareAppMessage: function(ops) {
    var that = this
    var act = that.data.list[that.data.shareindex]
    if (ops.from === 'button') { //页面内转发按钮     

    } else {
      return {
        title: '邀请您来同感Live分享现场',
        desc: '邀请您来同感Live分享现场',
        path: '/pages/index/index',
        imageUrl: 'http://simul.dpaper.cn/miniprogram/show_images/share_logo.jpeg',
        success: function(res) {},
        fail: function(res) {}
      }
    }
    //11
    return {
      title: act.begin.monthOri + '-' + act.begin.dayOri + '•' + act.area + '\n' + act.name,
      desc: act.name,
      path: '/pages/detail/detail?uuid=' + act.id + '&source=app&commId=0&type=0',
      imageUrl: that.data.sharepicurl ? that.data.sharepicurl : act.acti_photo,
      success: function(res) { // 转发成功       
        var shareTickets = res.shareTickets;
        if (shareTickets.length == 0) {
          return false;
        }
        //可以获取群组信息
        if (that.data.systemInfo.platform == 'android' && (shareTickets.length > 0)) {
          wx.getShareInfo({
            shareTicket: shareTickets[0],
            success: function(res) {
              wx.showToast({
                title: "分享成功",
                duration: 2000
              });
            },
            fail: function() {
              wx.showToast({
                title: "分享失败",
                duration: 2000
              });
            }
          })
        }
        if (that.data.systemInfo.platform == 'ios' && (shareTickets.length > 0)) {
          wx.showToast({
            title: "分享成功",
            duration: 2000
          });
        }
      },
      fail: function(res) { // 转发失败        
        wx.showToast({
          title: "分享失败，请重新分享",
          duration: 2000
        });
      }
    }
    //11
  },
  maskmove: function() {
    console.log('穿透')
    return
  },
  cancleMask: function() {
    this.setData({
      hiddenAll: true,
      hiddenShare: true,
      hiddenNavigation: true,
      hiddenWXShare: true,
      sharepicurl: ''
    })
  },
  // 处理分享海报结束

  // 授权触发刷新
  onAuthChanged: function() {
    this.GetList(this, 1);
  },

  onDataChanged: function(changedData) {
    console.log('接守到详情页的数据')
    console.log(changedData)
    var that = this
    for (var i = 0; i < that.data.list.length; i++) {
      let oneAct = that.data.list[i]
      if (oneAct.id == changedData.data.id) {
        var followers = 'list[' + i + '].followers';
        var mefav = 'list[' + i + '].hasCollect';
        var collectCount = 'list[' + i + '].collectCount';
        var count = oneAct.collectCount
        if (changedData.action > 0) {
          count++;
        } else {
          count--;
        }
        that.setData({
          [followers]: changedData.data.followers,
          [mefav]: changedData.data.hasCollect,
          [collectCount]: count,
        });
        break
      }
    }
  },

  onSlideChangeEnd: function(e) {
    var that = this;
    var current = e.detail.current
    this.setData({
      preIndex: current
    })
    console.log(that.data.preIndex)
  },
  changeFinish: function(event) {
    var currentIndex = event.detail.current
    this.setData({
      preIndex: currentIndex
    })


  },
  bindDownLoad: function() {
    var that = this;
    that.showLoadTip()
    that.GetList(that, 2);
  },

  refresh: function(event) {
    this.setData({
      page: 1,
      uphidden: false,
      scrollTop: 0
    });
    this.GetList(this, 1)
  },

  //关注 
  follow: function(e) {
    var that = this
    that.auth = that.selectComponent("#auth");
    if (that.data.auth && that.data.hasPhone) {
      let index = e.currentTarget.dataset.index
      var uuid = that.data.list[index]
      util.pututrequest(api.collectActivity, 'POST', {
        id: uuid.id
      }).then(res => {
        if (res && res.code == 200) {
          var fnew = []
          if (uuid.followers) {
            fnew = uuid.followers
          }
          fnew.push(that.data.userInfo)
          if (fnew.length > 3) {
            fnew.shift()
          }

          var followers = 'list[' + index + '].followers';
          var mefav = 'list[' + index + '].hasCollect';
          var count = uuid.collectCount
          var collectCount = 'list[' + index + '].collectCount';
          that.setData({
            [followers]: fnew,
            [collectCount]: count + 1,
            [mefav]: true
          });
          //关注成功提示
          wx.showToast({
            title: '已加入“想去”',
            icon: 'success',
            duration: 2000
          })
        } else {
          wx.showToast({
            title: '已经收藏过啦',
            icon: 'success',
            duration: 2000
          })
        }
      });
      // 处理业务
    } else {
      that.auth.showAuth();
    }
  },
  //取消关注
  cancelFollow: function(e) {
    var that = this
    let index = e.currentTarget.dataset.index
    var uuid = that.data.list[index]

    util.pututrequest(api.collectActivity + '?id=' + uuid.id, 'DELETE').then(res => {
      if (res && res.code == 200) {
        uuid.hasCollect = false
        var fnew = uuid.followers
        var delId = 0
        var followers = 'list[' + index + '].followers';
        var hasFollow = 'list[' + index + '].hasCollect';
        for (var i = 0; i < fnew.length; i++) {
          let oneFollow = fnew[i]
          console.log(oneFollow)
          if (oneFollow.id == app.globalData.userInfo.id) {
            delId = i
            break
          }
        }
        fnew.splice(delId, 1)
        var count = uuid.collectCount
        var collectCount = 'list[' + index + '].collectCount';
        this.setData({
          [followers]: fnew,
          [collectCount]: count - 1,
          [hasFollow]: false,
        })
        wx.showToast({
          title: '我不想去啦',
          icon: 'success',
          duration: 2000
        })
      }
    })
  },

  gotoDetail: function(e) {
    var that = this;
    if (!that.data.isShowDate) {
      var index = e.currentTarget.dataset.index
      var item = that.data.list[index]
      wx.navigateTo({
        url: '/pages/detail/detail?uuid=' + item.id + '&source=index&commId=0&type=0',
        success: function() {},
        fail: function() {},
        complete: function() {}
      })
    }
  },

  goUpload: function(e) {
    var that = this;
    if (!that.data.isShowDate) {
      wx.navigateTo({
        url: '/pages/search/search',
        success: function() {},
        fail: function() {},
        complete: function() {}
      })
    }
  },


  click_blank: function(e) {
    this.setData({
      isShowDate: false,
    })
  },
  showAllDate: function() {
    if (this.data.isShowDate) {
      this.setData({
        isShowDate: false,

      })
    } else {
      this.getAll(this.data.checkInDate, this.data.checkOutDate);
      let toView = this.dateToView();
      this.setData({
        isShowDate: true,
        markcheckInDate: false, //标记开始时间是否已经选择
        markcheckOutDate: false, //标记结束时间是否已经选择
        toView: toView
      })
    }
  },

  dateToView: function() {
    var dateStr = ''
    if (this.data.checkInDate) {
      var dateArry = this.data.checkInDate.split("-")
      let year = dateArry[0]
      let month = dateArry[1]
      let day = dateArry[2]
      if (month.indexOf("0") == 0) {
        month = month.substring(1)
      }

      dateStr = 'flag' + year + month
      return dateStr;
    }
  },

  showDate: function() {
    this.setData({
      isShowDate: true,
    })
  },

  hideDate: function() {
    this.setData({
      isShowDate: false,
    })
  },
  //地理位置导航
  intoMap: function(e) {
    var item = e.currentTarget.dataset.geo
    if (item && item.venue) {
      wx.openLocation({ //所以这里会显示你当前的位置
        latitude: Number(item.venue.latitude),
        longitude: Number(item.venue.longitude),
        name: item.area,
        address: item.area,
        scale: 16
      })
    }
  },

  followApp: function() {
    wx.getSystemInfo({
      success: function(res) {
        let type = res.system
        if (type.indexOf("Android") != -1) {
          wx.showModal({
            title: '跳转至同感App',
            content: '亲爱的主人，很遗憾,同感app暂时未支持您的设备类型,您还是在小程序里尽情玩耍吧！'
          })
        }
        if (type.indexOf("iOS") != -1) {
          wx.showModal({
            title: '跳转至同感App',
            content: '亲爱的主人，请到AppStore里下载同感App查看更多同感动态！'
          })
        }
      }
    })
  },

  //时间函数
  createDateListData: function() {
    var dateList = [];
    var now = new Date();
    /*
      设置日期为 年-月-01,否则可能会出现跨月的问题
      比如：2017-01-31为now ,月份直接+1（now.setMonth(now.getMonth()+1)），则会直接跳到跳到2017-03-03月份.
        原因是由于2月份没有31号，顺推下去变成了了03-03
    */
    now = new Date(now.getFullYear(), now.getMonth(), 1);
    for (var i = 0; i < this.data.maxMonth; i++) {
      var momentDate = Moment(now).add(this.data.maxMonth - (this.data.maxMonth - i), 'month').date;
      var year = momentDate.getFullYear() - 1; //弹开第一眼看到的年份
      var month = momentDate.getMonth() + 1; //展示哪个月开始

      var days = [];
      var totalDay = this.getTotalDayByMonth(year, month);
      var week = this.getWeek(year, month, 1);
      //-week是为了使当月第一天的日期可以正确的显示到对应的周几位置上，比如星期三(week = 2)，
      //则当月的1号是从列的第三个位置开始渲染的，前面会占用-2，-1，0的位置,从1开正常渲染
      for (var j = -week + 1; j <= totalDay; j++) {
        var tempWeek = -1;
        if (j > 0)
          tempWeek = this.getWeek(year, month, j);
        var clazz = '';
        if (tempWeek == 0 || tempWeek == 6)
          clazz = 'week'
        // if (j < DATE_DAY && year == DATE_YEAR && month == DATE_MONTH) ****
        //   //当天之前的日期不可用
        //   clazz = 'unavailable ' + clazz;
        // else
        //   clazz = 'nostate ' + clazz
        clazz = 'nostate ' + clazz;
        days.push({
          day: j,
          class: clazz
        })
      }
      var dateItem = {
        id: year + '-' + month,
        year: year,
        month: month,
        days: days
      }

      dateList.push(dateItem);
    }
    this.setData({
      dateList: dateList
    });
    DATE_LIST = dateList;
  },
  /*
   * 获取月的总天数
   */
  getTotalDayByMonth: function(year, month) {
    month = parseInt(month, 10);
    var d = new Date(year, month, 0);
    return d.getDate();
  },
  /*
   * 获取月的第一天是星期几
   */
  getWeek: function(year, month, day) {
    var d = new Date(year, month - 1, day);
    return d.getDay();
  },
  /**
   * 点击日期事件
   */
  onPressDate: function(e) {
    //清除上一次选中的那些日期
    if (!this.data.markcheckInDate && !this.data.markcheckOutDate) {
      this.movePressStyle();
    }

    var {
      year,
      month,
      day
    } = e.target.dataset;

    //当前选择的日期为同一个月并小于今天，或者点击了空白处（即day<0），不执行 ****
    // if ((day < DATE_DAY && month == DATE_MONTH) || day <= 0) return;

    var tempMonth = month;
    var tempDay = day;

    if (month < 10) tempMonth = '0' + month
    if (day < 10) tempDay = '0' + day

    var date = year + '-' + tempMonth + '-' + tempDay;

    if (this.data.markcheckInDate && this.data.markcheckOutDate) {
      this.movePressStyle();
      this.setData({
        checkInDate: date,
        checkInDateStr: Moment(date).format('MM.DD'),
        markcheckInDate: true,

        markcheckOutDate: false,
        checkOutDate: '',
        checkOutDateStr: '',
      });
      this.renderPressStyle(year, month, day);
      return;
    }

    if (!this.data.markcheckInDate) {
      this.setData({
        checkInDate: date,
        checkInDateStr: Moment(date).format('MM.DD'),
        markcheckInDate: true,
      });
    } else if (!this.data.markcheckOutDate) {
      this.setData({
        checkOutDate: date,
        checkOutDateStr: Moment(date).format('MM.DD'),
        markcheckOutDate: true,
      });
      //设缓存，返回页面时，可在onShow时获取缓存起来的日期
      wx.setStorage({
        key: 'TONGGAN_SOURCE_DATE',
        data: {
          checkInDate: this.data.checkInDate,
          checkOutDate: this.data.checkOutDate,
          checkInDateStr: Moment(this.data.checkInDate).format('MM.DD'),
          checkOutDateStr: Moment(this.data.checkOutDate).format('MM.DD')
        }
      });
      wx.navigateBack({
        delta: 1, // 回退前 delta(默认为1) 页面
      });
    }

    if (this.data.markcheckInDate && !this.data.markcheckOutDate) {
      this.renderPressStyle(year, month, day);
    }

    if (this.data.markcheckOutDate && this.data.markcheckInDate) {
      this.getAll(this.data.checkInDate, this.data.checkOutDate);
    }

  },


  renderPressStyle: function(year, month, day) {
    var dateList = this.data.dateList;
    for (var i = 0; i < dateList.length; i++) {
      var dateItem = dateList[i];
      var id = dateItem.id;
      if (id === year + '-' + month) {
        var days = dateItem.days;
        for (var j = 0; j < days.length; j++) {
          var tempDay = days[j].day;
          if (tempDay == day) {
            days[j].class = days[j].class + ' active';
            break;
          }
        }
        break;
      }
    }
    this.setData({
      dateList: dateList
    });
  },

  movePressStyle: function() {
    var dateList = this.data.dateList;
    for (var i = 0; i < dateList.length; i++) {
      var dateItem = dateList[i];
      var id = dateItem.id;

      var days = dateItem.days;
      for (var j = 0; j < days.length; j++) {
        days[j].class = 'date-day nostate';
      }
    }
    this.setData({
      dateList: dateList
    });
  },

  serachAct: function() {
    if (this.data.markcheckInDate && this.data.markcheckOutDate) {
      this.setData({
        isShowDate: false,
        nomore: false,

      });
      this.GetList(this, 1);
    } else {
      wx.showModal({
        title: '友情提示',
        showCancel: false,
        content: '请准确选择起始和结束时间'
      })
    }
  },


  getAll: function(begin, end) {
    var that = this
    var dateList = that.data.dateList;
    var ab = begin.split("-");
    var ae = end.split("-");
    var db = new Date();
    db.setUTCFullYear(ab[0], ab[1] - 1, ab[2]);
    var de = new Date();
    de.setUTCFullYear(ae[0], ae[1] - 1, ae[2]);
    var unixDb = db.getTime();
    var unixDe = de.getTime();
    for (var k = unixDb; k <= unixDe;) {
      var tt = (new Date(parseInt(k)))
      var dayOne = tt.getDate()
      var yearOne = tt.getFullYear()
      var monthOne = tt.getMonth() + 1
      for (var i = 0; i < dateList.length; i++) {
        var dateItem = dateList[i];
        var id = dateItem.id;
        if (id === yearOne + '-' + monthOne) {
          var days = dateItem.days;
          for (var j = 0; j < days.length; j++) {
            var tempDay = days[j].day;
            if (tempDay == dayOne) {
              days[j].class = days[j].class + ' active';
              break;
            }
          }
          break;
        }
      }
      k = k + 24 * 60 * 60 * 1000;
    }
    that.setData({
      dateList: dateList
    });

  },

  // 翻页
  //下拉刷新监听函数
  _onPullDownRefresh: function() {
    this.GetList(this, 1)
    this.setData({
      refreshing: false,
    });
  },

  //加载更多监听函数
  _onLoadmore: function() {
    var that = this;
    that.GetList(that, 2);
  },
  _onScroll: function(e) {

  },

  onPullDownRefresh() {
    var that = this
    that.GetList(this, 1)
    wx.stopPullDownRefresh();
  },
  onReachBottom() {
    var that = this
    that.GetList(that, 2);
  },

})